package com.ct.ecommerce.gateway.config;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ct.ecommerce.framework.constant.SecurityConstants;
import java.time.Duration;
import javax.annotation.Resource;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import reactor.core.publisher.Mono;

/**
 * @author changtong
 * @since 2021/6/2
 */
@Configuration
public class RouteConfig {
    @Resource
    private RedisTemplate redisTemplate;

    @Bean
    public RouteLocator routes(RouteLocatorBuilder builder) {
        return builder.routes().route("authorization-server-route-id",
            r -> r.path("/oauth/**")
                .filters(f -> f.modifyResponseBody(String.class, String.class, (exchange, s) -> {
                    String path = exchange.getRequest().getPath().value();
                    //获取token
                    if(path.equalsIgnoreCase(SecurityConstants.AUTH_TOKEN_PATH)){
                        //s是相应
                        if(StringUtils.hasText(s)){
                            //拿到token
                            JSONObject response = JSONUtil.parseObj(s);
                            String accessToken = response.getStr("access_token");
                            if (StringUtils.hasText(accessToken)) {
                                Long expiresIn = response.getLong("expires_in");
                                redisTemplate.opsForValue().set(accessToken,"", Duration.ofSeconds(expiresIn));
                            }
                        }
                    }
                    return Mono.just(s);
                })).uri("lb://authorization-server")).build();
    }

}
